<?php

class Ws{

    const HOST = '0.0.0.0';
    const PORT = '10007';

    private $ws = null;

    public function __construct()
    {
        $this->ws = new \Swoole\WebSocket\Server(self::HOST, self::PORT);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    /**
     * 监听客户端连接
     * @param $ws
     * @param $request
     */
    function onOpen($ws, $request){
        echo "新连接: ".$request->fd.PHP_EOL;

        //每隔两秒执行一次
        swoole_timer_tick(2000, function ($timer_id){
            echo $timer_id.": ".time().PHP_EOL;
        });
    }

    /**
     * 监听客户端消息
     * @param $ws
     * @param $frame
     */
    function onMessage($ws, $frame){
        echo "新数据: ".$frame->data.PHP_EOL;

        //5秒后执行
        swoole_timer_after(5000, function () use ($ws, $frame){
            echo "5s后执行";
            $ws->push($frame->fd, "server time: ".time());
        });

        //给客户端返回数据
        $ws->push($frame->fd, "服务器时间: ".time());
    }

    /**
     * 断开连接
     * @param $ws
     * @param $fd
     */
    function onClose($ws, $fd){
        echo "连接关闭: ".$fd.PHP_EOL;
    }

}

new Ws();




